package com.example.origin.finance.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.origin.finance.dto.XueqiuCashFlow;
import com.example.origin.finance.service.AbstractMultiStoreService;
import com.example.origin.resttemplate.util.RestUtil;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.util.HashMap;
import java.util.Map;

@Service
public class XueqiuCashFlowMultiStoreService extends AbstractMultiStoreService<XueqiuCashFlow> {


    // https://stock.xueqiu.com/v5/stock/finance/cn/cash_flow.json?symbol=SZ002594&type=all&is_detail=true&count=50&timestamp=1703921370791
    @Override
    protected void fillMap(String code, MultiValueMap<String, XueqiuCashFlow> linkedMultiValueMap) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("is_detail", "true");
        paramMap.put("type", "all");
        paramMap.put("count", "" + 50);
        paramMap.put("timestamp", "" + System.currentTimeMillis());
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Cookie", getXueqiuCookie());
        String u1 = "https://stock.xueqiu.com/v5/stock/finance/cn/cash_flow.json";

        if (!setParamMap(code, paramMap)) {
            return;
        }
        ResponseEntity<Object> response = RestUtil.restGet(restTemplate, u1, paramMap, headerMap, ParameterizedTypeReference.forType(Map.class));

        JSONObject jsonObject = JSONUtil.parseObj(response).getJSONObject("body").getJSONObject("data");

        JSONArray jsonArray = jsonObject.get("list", JSONArray.class);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            Map<String, Object> stringMap = new HashMap<>();
            stringMap.put("code", code);
            stringMap.put("symbol", paramMap.get("symbol"));
            for (Map.Entry<String, Object> stringObjectEntry : jsonObject1.entrySet()) {
                String key = stringObjectEntry.getKey();
                Object value = stringObjectEntry.getValue();
                if (!(value instanceof JSONArray)) {
                    stringMap.put(key, value);
                    continue;
                }
                JSONArray jsonArray1 = new JSONArray(value);
                Double value1 = jsonArray1.getDouble(0);
                stringMap.put(key, value1);
            }
            XueqiuCashFlow bean = BeanUtil.mapToBean(stringMap, XueqiuCashFlow.class, false, CopyOptions.create());
            linkedMultiValueMap.add(bean.getCode(), bean);
        }

    }

}
